<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/1/20
 * Time: 15:01
 */
class circleControl extends mobileHomeControl
{

    protected $identity = 0;    // 身份 0游客 1圈主 2管理 3成员 4申请中 5申请失败 6禁言
    protected $c_id = 0;        // 圈子id
    protected $cm_info = array();   // Members of the information
    protected $m_readperm = 0;  // Members read permissions
    protected $super = 0;
    protected $circleInfo;
    protected $theme_info;
    protected $t_id = 0;

    public function __construct()
    {
        parent::__construct();

    }

    /**
     * 圈子信息
     */
    protected function circleInfo()
    {
        $model = Model();
        $this->circleInfo = $model->table('circle')->where(array('circle_id' => $this->c_id))->find();
        if (empty($this->circleInfo)) {
            showMessage(L('circle_group_not_exists'), '', '', 'error');
        }
    }

    /**
     * 圈主和管理信息
     */
    protected function manageList()
    {
        $prefix = 'circle_managelist';
        $info = rcache($this->c_id, $prefix);
        if (empty($info)) {
            $manager_list = Model()->table('circle_member')->where(array('circle_id' => $this->c_id, 'is_identity' => array('in', array(1, 2))))->select();
            $manager_list = array_under_reset($manager_list, 'is_identity', 2);
            $manager_list[2] = array_under_reset($manager_list[2], 'member_id', 1);
            $info['info'] = serialize($manager_list);
            wcache($this->c_id, $info, $prefix, 60);
        }
        $manager_list = unserialize($info['info']);
        Tpl::output('creator', $manager_list[1][0]);
        Tpl::output('manager_list', $manager_list[2]);
    }

    /**
     * 会员信息
     */
    protected function memberInfo()
    {
        $member_id = $this->getMemberIdIfExists();
        if ($member_id && !$_SESSION['is_login'] && !$_SESSION['member_id']) {
            $_SESSION['is_login'] = 1;
            $_SESSION['member_id'] = $member_id;
        }
        if ($_SESSION['is_login']) {
            $this->cm_info = Model()->table('circle_member')->where(array('circle_id' => $this->c_id, 'member_id' => $_SESSION['member_id']))->find();
            if (!empty($this->cm_info)) {
                switch (intval($this->cm_info['cm_state'])) {
                    case 1:
                        $this->identity = intval($this->cm_info['is_identity']);
                        break;
                    case 0:
                        $this->identity = 4;
                        break;
                    case 2:
                        $this->identity = 5;
                        break;
                }
                // 禁言
                if ($this->cm_info['is_allowspeak'] == 0) {
                    $this->identity = 6;
                }
            }
            Tpl::output('cm_info', $this->cm_info);
        }
        Tpl::output('identity', $this->identity);
    }

    /**
     * Read permissions
     */
    protected function readPermissions($cm_info)
    {
        $data = rkcache('circle_level', true);
        $rs = array();
        $rs[0] = 0;
        $rs[0] = L('circle_no_limit');
        foreach ($data as $v) {
            $rs[$v['mld_id']] = $v['mld_name'];
        }
        switch ($cm_info['is_identity']) {
            case 1:
            case 2:
                $rs['255'] = L('circle_administrator');
                $this->m_readperm = 255;
                return $rs;
                break;
            case 3:
                $rs = array_slice($rs, 0, intval($cm_info['cm_level']) + 1, true);
                $this->m_readperm = $cm_info['cm_level'];
                return $rs;
                break;
        }
    }

    /**
     * 话题信息
     */
    protected function themeInfo()
    {
        $this->t_id = intval($_GET['t_id']);
        if ($this->t_id <= 0) {
            @header("location: " . CIRCLE_SITE_URL);
        }
        Tpl::output('t_id', $this->t_id);

        $this->theme_info = Model()->table('circle_theme')->where(array('circle_id' => $this->c_id, 'theme_id' => $this->t_id))->find();
        if (empty($this->theme_info)) {
            showMessage(L('circle_theme_not_exists'), '', '', 'error');
        }
    }

    /**
     * 首页 话题列表
     */
    public function indexOp()
    {

        $this->c_id = $_GET['c_id'];
//        if(empty($_SESSION['member_id'])){
//                 output_data(array("code"=>400));
//                 exit();
//         }
        // 圈子信息
        $this->circleInfo();
        // 圈主和管理信息
        $this->manageList();
        // 会员信息
        $this->memberInfo();

        $model = Model();
        if (!empty($_SESSION['member_id'])) {
            // Membership level information
            $data = rkcache('circle_level', true);
            $member = Model('member')->getMemberInfoByID($_SESSION['member_id'], 'member_name');
            // 查询会员是否加入该圈子
            $res = $model->table('circle_member')->where(array("member_id" => $_SESSION['member_id'], "circle_name" => $this->circleInfo['circle_name']))->select();
            // 自动加入圈子
            if (empty($res)) {
                $model = Model();
                $insert = array();
                $insert['cm_applycontent'] = $_POST['apply_content'];
                $insert['cm_intro'] = $_POST['intro'];
                $insert['member_id'] = $_SESSION['member_id'];
                $insert['circle_id'] = $this->c_id;
                $insert['circle_name'] = $this->circleInfo['circle_name'];
                $insert['member_name'] = $member['member_name'];
                $insert['cm_applytime'] = $insert['cm_jointime'] = time();
                $insert['cm_level'] = $data[1]['mld_id'];
                $insert['cm_levelname'] = $data[1]['mld_name'];
                $insert['cm_exp'] = 1;
                $insert['cm_nextexp'] = $data[2]['mld_exp'];
                $insert['cm_state'] = intval($this->circle_info['circle_joinaudit']) == 0 ? 1 : 0;
                $insert['is_identity'] = 3;
//                $model->table('circle_member')->pk(array('member_id', 'circle_id'))->insert($insert, true);
                $model->table('circle_member')->insert($insert, true);
                if (intval($this->circle_info['circle_joinaudit']) == 0) {
                    // Update the number of members
                    $update = array(
                        'circle_mcount' => array('exp', 'circle_mcount+1')
                    );
                    $model->table('circle')->where(array('circle_id' => $this->c_id))->update($update);
                    header("Location:?act=circle&op=index&c_id=" . $this->c_id);
                } else {
                    // Update is applying for membership
                    $update = array(
                        'new_verifycount' => array('exp', 'new_verifycount+1')
                    );
                    $model->table('circle')->where(array('circle_id' => $this->c_id))->update($update);
                    showDialog(L('nc_apply_op_succ'), 'reload', 'succ', 'CUR_DIALOG.close();');
                }
            }
        }
        if ($_GET['page']) {
            $page = $_GET['page'];
        } else {
            $page = 1;
        }
        $pagenum = 5;
        $startlimit = ($page - 1) * $pagenum;
        // 话题列表
        $where = array();
        $where['circle_id'] = $this->c_id;
        $thc_id = intval($_GET['thc_id']);
        if ($thc_id > 0) {
            $where['thclass_id'] = $thc_id;
            Tpl::output('thc_id', $thc_id);
        }
        if (intval($_GET['cream']) == 1) {
            $where['is_digest'] = 1;
        }
        $theme_list = $model->table('circle_theme')->where($where)->order('is_stick desc,lastspeak_time desc')->limit("$startlimit,$pagenum")->select();
        // 限制图片个数
        foreach ($theme_list as $k => $v) {
            $theme_list[$k]['wap_content'] = msubstr($v['wap_content'], 0, 100);
            $imageList = explode(',', trim($v['wap_imgs'], ','));
            $theme_list[$k]['imageSize'] = explode(',', trim($v['imagesize'], ','));
            $ThumbList = [];
            $width = 140;
            $height = 140;
            foreach ($imageList as $c=>$value) {
                $thumb = substr($value, 0, strripos($value, '.'));
                $iwidth = intval(strstr( $theme_list[$k]['imageSize'][$c],'X',true));
                if ( $iwidth < $width) {
                    $ThumbList[] = $thumb . substr($value, strripos($value, '.'));
                } else {
                    $ThumbList[] = $thumb . $width . "X" . $height . substr($value, strripos($value, '.'));
                }
            }
            $theme_list[$k]['theme_addtime'] = date("Y-m-d H:i:s", $v['theme_addtime']);
            $theme_list[$k]['imags'] = array_slice($imageList, 0, 9);
            $theme_list[$k]['thumblist'] = $ThumbList;
            $member_avatar = $model->table('member')->where(array("member_id" => $v['member_id']))->field("member_avatar")->find();
            $theme_list[$k]['avator'] = $member_avatar['member_avatar'];
        }

        output_data($theme_list);
        die;

        // Read Permission
        $readperm = $this->readPermissions($this->cm_info);
        // breadcrumb navigation
        $this->breadcrumd();
//
    }

    public function themeOp()
    {
        $this->c_id = $_GET['c_id'];
        if ($_SESSION['is_login']) {
            $is_login = 1;
        }
        // 圈子信息
        $this->circleInfo();

        // 圈主和管理信息
        $this->manageList();

        // 会员信息
        $this->memberInfo();

        // 话题信息
        $this->themeInfo();
        // 限制图片个数
        $this->theme_info['wap_content'] = msubstr($this->theme_info['wap_content'], 0, 100);
        if (!empty($this->theme_info['wap_imgs'])) {
            $imageList = explode(',', trim($this->theme_info['wap_imgs'], ','));
            $ThumbList = [];
            $this->theme_info['imageSize'] = explode(',', trim($this->theme_info['imagesize'], ','));
            $width = 140;
            $height = 140;
            foreach ($imageList as $k=>$value) {
                $thumb = substr($value, 0, strripos($value, '.'));

                $ThumbList[] = $thumb . $width . "X" . $height . substr($value, strripos($value, '.'));
            }
            $this->theme_info['thumblist'] = $ThumbList;

            $this->theme_info['imags'] = array_slice($imageList, 0, 9);
        }

        if ($_GET['page']) {
            $page = $_GET['page'];
        } else {
            $page = 1;
        }
        $pagenum = 5;
        $startlimit = ($page - 1) * $pagenum;

        // Verify the read permissions
        $this->readPermissions($this->cm_info);
        if ($this->m_readperm < $this->theme_info['theme_readperm']) {
            showMessage(L('circle_Insufficient_permissions'), CIRCLE_SITE_URL, '', 'error');
        }
        $member_avatar = model()->table('member')->where(array("member_id" => $this->theme_info['member_id']))->field("member_avatar")->find();
        $this->theme_info['avatar'] = $member_avatar['member_avatar'];
        $this->theme_info['theme_addtime'] = date("Y-m-d H:i:s", $this->theme_info['theme_addtime']);
        $model = Model();
        // 话题被浏览数增加
        $model->table('circle_theme')->where(array('theme_id' => $this->t_id))->update(array('theme_browsecount' => array('exp', 'theme_browsecount+1')));

        // 回复列表
        $where = array();
        $where['theme_id'] = $this->t_id;
        if ($_GET['only_id'] != '') {
            $where['member_id'] = intval($_GET['only_id']);
        }
        $reply_info = $model->table('circle_threply')->where($where)->limit("$startlimit,$pagenum")->order('reply_id DESC')->select();
        foreach ($reply_info as $k => $val) {
            $member_avatar = model()->table('member')->where(array("member_id" => $val['member_id']))->field("member_avatar")->find();
            $reply_info[$k]['avatar'] = $member_avatar['member_avatar'];
            $reply_info[$k]['reply_addtime'] = date("Y-m-d H:i:s", $val['reply_addtime']);
        }
        output_data(array("theme" => $this->theme_info, 'reply' => $reply_info, 'is_login' => $is_login ? $is_login : 0));
    }

    /**
     * 发布论坛
     */
    Public function discuss_addOp()
    {
        $this->c_id = $_POST['cid'];
        $member_id = $this->getMemberIdIfExists();
        if ($member_id && !$_SESSION['is_login'] && !$_SESSION['member_id']) {
            $_SESSION['is_login'] = 1;
            $_SESSION['member_id'] = $member_id;
        }
        $member_info = Model('member')->getMemberInfoByID($member_id);
        // 圈子信息
        $this->circleInfo();
        $model = Model();

        // 主题分类
        $thclass_id = intval($_POST['thtype']);
        $thclass_name = '';
        if ($thclass_id > 0) {
            $thclass_info = $model->table('circle_thclass')->where(array('thclass_id' => $thclass_id))->find();
            $thclass_name = $thclass_info['thclass_name'];
        }
        /**
         * 验证
         */
        $obj_validate = new Validate();
        $validate_arr[] = array("input" => $_POST["title"], "require" => "true", "message" => Language::get('nc_name_not_null'));
        $validate_arr[] = array("input" => $_POST["title"], "validator" => 'Length', "min" => 4, "max" => 30, "message" => Language::get('nc_name_min_max_length'));
        $validate_arr[] = array("input" => $_POST["content"], "require" => "true", "message" => Language::get('nc_content_not_null'));
        if (intval(C('circle_contentleast')) > 0) $validate_arr[] = array("input" => $_POST["themecontent"], "validator" => 'Length', "min" => intval(C('circle_contentleast')), "message" => Language::get('circle_contentleast'));
        $obj_validate->validateparam = $validate_arr;
        $error = $obj_validate->validate();
        if ($error != '') {
            output_error($error);
        }
        // 图片上传
        if ($_POST['thumb']) {
            $res = $this->upImgs($_POST['thumb'], BASE_UPLOAD_PATH . '/discuss');
        }
        $imagePath = "";
        $imageSize = "";
        if ($res) {
            foreach ($res as $v) {
                $file = $v;
                if (file_exists(BASE_ROOT_PATH.$v)) {
                    $file =  BASE_ROOT_PATH.$v;
                }
                $imageSizeInfo = getimagesize($file);
                $width = $imageSizeInfo[0];
                $heigth = $imageSizeInfo[1];
                $imageSize .= $width . "X" . $heigth . ",";
                $imagePath .= basename($v) . ",";
                if (!file_exists(BASE_ROOT_PATH.$v)) {
                    $imagefix = substr($v, strripos($v, '.'));
                    $imagepix = substr($v, 0, strripos($v, '.'));
                    // 目标图路径
                    $whidth = 140;
                    $heigth = 140;
                    $dis_path = $imagepix . $whidth . "X" . $heigth . $imagefix;
                    $res = $this->resize($v, $dis_path, $whidth, $heigth); // 生成缩略图
                }
            }
        }
        $insert = array();
        $insert['theme_name'] = $this->circleCenterCensor($_POST['title']);
        $insert['theme_content'] = $this->circleCenterCensor($_POST['content']);
        $insert['circle_id'] = $this->c_id;
        $insert['circle_name'] = $this->circleInfo['circle_name'];
        $insert['thclass_id'] = $thclass_id;
        $insert['thclass_name'] = $thclass_name;
        $insert['member_id'] = $_SESSION['member_id'];
        $insert['member_name'] = $member_info['member_name'];
        $insert['is_identity'] = $this->identity;
        $insert['theme_addtime'] = time();
        $insert['lastspeak_time'] = time();
        $insert['wap_content'] = $this->circleCenterCensor($_POST['content']);
        $insert['theme_readperm'] = intval($_POST['readperm']);
        $insert['theme_special'] = intval($_GET['sp']);
        $insert['imagesize'] = $imageSize;
        $insert['wap_imgs'] = $imagePath;
        if ($_POST['id']) {
            $where['theme_id'] = $_POST['id'];
            if (empty($_POST['thumb'])) {
                $insert['wap_imgs'] = '';
            }
            $themeid = $model->table('circle_theme')->where($where)->update($insert);
            if (!$themeid) {
                output_error('编辑失败');
            }
            output_data(array('status' => 200, 'msg' => "编辑成功"));
        }
        $themeid = $model->table('circle_theme')->insert($insert);
        if ($themeid) {
            $has_goods = 0; // 存在商品标记
            $has_affix = 0; // 存在附件标记
            // 插入话题商品
            if (!empty($_POST['goods'])) {
                $goods_insert = array();
                foreach ($_POST['goods'] as $key => $val) {
                    $p = array();
                    $p['theme_id'] = $themeid;
                    $p['reply_id'] = 0;
                    $p['circle_id'] = $this->c_id;
                    $p['goods_id'] = $val['id'];
                    $p['goods_name'] = $val['name'];
                    $p['goods_price'] = $val['price'];
                    $p['goods_image'] = $val['image'];
                    $p['store_id'] = $val['storeid'];
                    $p['thg_type'] = $val['type'];
                    $p['thg_url'] = ($val['type'] == 1) ? $val['uri'] : '';
                    $goods_insert[] = $p;
                }
                $rs = $model->table('circle_thg')->insertAll($goods_insert);
                $has_goods = 1;
            }
            // 更新话题附件
            $model->table('circle_affix')->where(array('affix_type' => 1, 'member_id' => $_SESSION['member_id'], 'theme_id' => 0))->update(array('theme_id' => $themeid, 'circle_id' => $this->c_id));

            // 更新话题信息
            $affixe_count = $model->table('circle_affix')->where(array('affix_type' => 1, 'member_id' => $_SESSION['member_id'], 'theme_id' => $themeid))->count();
            if ($affixe_count > 0) {
                $has_affix = 1;
            }
            if ($has_goods || $has_affix) {
                $update = array();
                $update['has_goods'] = $has_goods;
                $update['has_affix'] = $has_affix;
                $model->table('circle_theme')->where(array('theme_id' => $themeid))->update($update);
            }

            // 更新圈子表话题数
            $update = array(
                'circle_thcount' => array('exp', 'circle_thcount+1')
            );
            $model->table('circle')->where(array('circle_id' => $this->c_id))->update($update);

            // 更新用户相关信息
            $update = array(
                'cm_thcount' => array('exp', 'cm_thcount+1'),
                'cm_lastspeaktime' => time()
            );
            $model->table('circle_member')->where(array('member_id' => $_SESSION['member_id'], 'circle_id' => $this->c_id))->update($update);

            // Special theme
            if ($_GET['sp'] == 1) {
                $insert = array();
                $insert['theme_id'] = $themeid;
                $insert['poll_multiple'] = intval($_POST['multiple']);
                $insert['poll_startime'] = time();
                $insert['poll_endtime'] = intval($_POST['days']) != 0 ? time() + intval($_POST['days']) * 60 * 60 * 12 : 0;
                $insert['poll_days'] = intval($_POST['days']);
                $model->table('circle_thpoll')->insert($insert);
                if (!empty($_POST['polloption'])) {
                    $insert_array = array();
                    foreach ($_POST['polloption'] as $val) {
                        if ($val == '') continue;
                        $option = array();
                        $option['theme_id'] = $themeid;
                        $option['pollop_option'] = $val;
                        $insert_array[] = $option;
                    }
                    $model->table('circle_thpolloption')->insertAll($insert_array);
                }
            }

            // set cookie of SEC
            if (intval(C('circle_intervaltime')) > 0) {
                setNcCookie('circle_intervaltime', true, intval(C('circle_intervaltime')));
            }

            // Experience
            $param = array();
            $param['member_id'] = $_SESSION['member_id'];
            $param['member_name'] = $this->cm_info['member_name'];
            $param['circle_id'] = $this->c_id;
            $param['type'] = 'release';
            $param['itemid'] = $themeid;
            Model('circle_exp')->saveExp($param);
            output_data(array('status' => 200, 'msg' => "发布成功"));
        } else {
            output_error('发布失败');
        }
    }

    /**
     * 添加评论
     */
    public function addCommentOp()
    {
        // Reply function does close,throw error.
        // 会员信息
        // 不是圈子成员不能发帖
        $this->c_id = $_GET['c_id'];
        $this->t_id = $_GET['t_id'];
        $this->memberInfo();
        // 话题信息
        $this->themeInfo();

        $member_id = $this->getMemberIdIfExists();
        if ($member_id && !$_SESSION['is_login'] && !$_SESSION['member_id']) {
            $_SESSION['is_login'] = 1;
            $_SESSION['member_id'] = $member_id;
        }

        /**
         * 验证
         */
        $obj_validate = new Validate();
        $obj_validate->validateparam = array(
            array("input" => $_GET["replycontent"], "require" => "true", "message" => L('circle_reply_not_null')),
        );
        $error = $obj_validate->validate();
        if ($error != '') {
            output_error($error);
        } else {
            $model = Model();
            $insert = array();
            $insert['theme_id'] = $this->t_id;
            $insert['circle_id'] = $this->c_id;
            $insert['member_id'] = $_SESSION['member_id'];
            $insert['member_name'] = $this->cm_info['member_name'];
            $insert['reply_content'] = $this->circleCenterCensor($_GET['replycontent']);
            $insert['reply_addtime'] = time();
            $insert['is_closed'] = 0;

            // 回复楼层验证
            if ($_POST['answer_id'] != '') {
                $reply_info = Model()->table('circle_threply')->where(array('theme_id' => $this->t_id, 'reply_id' => intval($_POST['answer_id'])))->find();
                if (!empty($reply_info)) {
                    $insert['reply_replyid'] = $reply_info['reply_id'];
                    $insert['reply_replyname'] = $reply_info['member_name'];
                }
            }

            $reply_id = $model->table('circle_threply')->insert($insert);
            $insert['reply_addtime'] = date("Y-m-d H:i:s", $insert['reply_addtime']);
            $insert['member_face'] = Model('member')->getMemberInfo(array("member_id" => $this->cm_info['member_id']), 'member_avatar');
            // 话题被回复数增加 最后发言人发言时间
            $update = array();
            $update['theme_commentcount'] = array('exp', 'theme_commentcount+1');
            $update['lastspeak_id'] = $_SESSION['member_id'];
            $update['lastspeak_name'] = $_SESSION['member_name'];
            $update['lastspeak_time'] = time();
            $model->table('circle_theme')->where(array('theme_id' => $this->t_id))->update($update);
            // 成员回复数增加 最后回复时间
            $model->table('circle_member')->where(array('member_id' => $_SESSION['member_id'], 'circle_id' => $this->c_id))->update(array('cm_comcount' => array('exp', 'cm_comcount+1'), 'cm_lastspeaktime' => time()));
            output_data(array('content' => $insert));
            if ($reply_id) {
                if ($_GET['type'] == 'adv') {
                    // 插入话题商品
                    if (!empty($_POST['goods'])) {
                        $goods_insert = array();
                        foreach ($_POST['goods'] as $key => $val) {
                            $p = array();
                            $p['theme_id'] = $this->t_id;
                            $p['reply_id'] = $reply_id;
                            $p['circle_id'] = $this->c_id;
                            $p['goods_id'] = $val['id'];
                            $p['goods_name'] = $val['name'];
                            $p['goods_price'] = $val['price'];
                            $p['goods_image'] = $val['image'];
                            $p['store_id'] = $val['storeid'];
                            $p['thg_type'] = $val['type'];
                            $p['thg_url'] = ($val['type'] == 1) ? $val['uri'] : '';
                            $goods_insert[] = $p;
                        }
                        $rs = $model->table('circle_thg')->insertAll($goods_insert);
                    }
                    // 更新话题附件
                    $model->table('circle_affix')->where(array('affix_type' => 2, 'member_id' => $_SESSION['member_id'], 'reply_id' => 0))->update(array('theme_id' => $this->t_id, 'reply_id' => $reply_id, 'circle_id' => $this->c_id));
                }

                // set cookie of SEC
                if (intval(C('circle_intervaltime')) > 0) {
                    setNcCookie('circle_intervaltime', true, intval(C('circle_intervaltime')));
                }

                if ($this->theme_info['member_id'] != $_SESSION['member_id']) {
                    // Experience for replyer
                    $param = array();
                    $param['member_id'] = $_SESSION['member_id'];
                    $param['member_name'] = $this->cm_info['member_name'];
                    $param['circle_id'] = $this->c_id;
                    $param['theme_id'] = $this->t_id;
                    $param['type'] = 'reply';
                    $param['itemid'] = $this->t_id . ',' . $reply_id;
                    Model('circle_exp')->saveExp($param);

                    // Experience for releaser
                    $param = array();
                    $param['member_id'] = $this->theme_info['member_id'];
                    $param['member_name'] = $this->theme_info['member_name'];
                    $param['theme_id'] = $this->t_id;
                    $param['circle_id'] = $this->c_id;
                    $param['type'] = 'replied';
                    $param['itemid'] = $this->t_id;
                    Model('circle_exp')->saveExp($param);

                }

            }
        }
    }

    /**
     * 赞
     */
    public function ajax_likeyesOp()
    {

        $member_id = $this->getMemberIdIfExists();
        if ($member_id && !$_SESSION['is_login'] && !$_SESSION['member_id']) {
            $_SESSION['is_login'] = 1;
            $_SESSION['member_id'] = $member_id;
        }

        $this->t_id = $_GET['t_id'];
        $like_info = Model()->table('circle_like')->where(array('theme_id' => $this->t_id, 'member_id' => $_SESSION['member_id']))->find();
        if (empty($like_info)) {
            // 插入话题赞表
            Model()->table('circle_like')->insert(array('theme_id' => $this->t_id, 'member_id' => $_SESSION['member_id'], 'circle_id' => $this->c_id));
            // 更新赞数量
            Model()->table('circle_theme')->where(array('theme_id' => $this->t_id))->update(array('theme_likecount' => array('exp', 'theme_likecount+1')));
            output_data(1);
        } else {
            output_data(0);
        }
    }

    // 获取我发布的
    public function mysendOp()
    {

        $member_id = $this->getMemberIdIfExists();
        if ($member_id && !$_SESSION['is_login'] && !$_SESSION['member_id']) {
            $_SESSION['is_login'] = 1;
            $_SESSION['member_id'] = $member_id;
        }
        $this->c_id = $_GET['type'];
        $model = Model();
        if ($_GET['page']) {
            $page = $_GET['page'];
        } else {
            $page = 1;
        }
        $pagenum = 30;
        $startlimit = ($page - 1) * $pagenum;

        // 话题列表
        $where = array();
        $where['circle_id'] = $this->c_id;
        $where['member_id'] = $member_id;
        $thc_id = intval($_GET['thc_id']);
        if ($thc_id > 0) {
            $where['thclass_id'] = $thc_id;
        }
        if (intval($_GET['cream']) == 1) {
            $where['is_digest'] = 1;
        }
        $theme_list = $model->table('circle_theme')->where($where)->order('is_stick desc,lastspeak_time desc')->limit("$startlimit,$pagenum")->select();
        foreach ($theme_list as $k => $v) {
            $theme_list[$k]['add_time'] = date("Y-m-d", $v['theme_addtime']);
        }
        output_data(array('themlist' => $theme_list));
        die;
    }

    // 获取我回复的
    public function myreplayOp()
    {

        $member_id = $this->getMemberIdIfExists();
        if ($member_id && !$_SESSION['is_login'] && !$_SESSION['member_id']) {
            $_SESSION['is_login'] = 1;
            $_SESSION['member_id'] = $member_id;
        }

        $member_id = $_SESSION['member_id'];
        $this->c_id = $_GET['c_id'];
        $where['member_id'] = $member_id;
        $where['circle_id'] = $this->c_id;
        $model = Model();
        if ($_GET['page']) {
            $page = $_GET['page'];
        } else {
            $page = 1;
        }
        $pagenum = 30;
        $startlimit = ($page - 1) * $pagenum;
        $theme_list = $model->table('circle_threply')->where($where)->limit("$startlimit,$pagenum")->select();
//        $theme_id = "";
//        foreach($theme_list as $key => $v){
//              $theme_id.=$v['theme_id'].',';
//        }
//        $themeid = implode(",",array_unique(explode(",",$theme_id)));
//        $condition['theme_id'] = array('in',trim($themeid));
//        $theme_list = $model->table('circle_theme')->where($condition)->order('is_stick desc,lastspeak_time desc')->limit("$startlimit,$pagenum")->select();
        foreach ($theme_list as $k => $v) {
            $theme_list[$k]['add_time'] = date("Y-m-d", $v['reply_addtime']);
        }
        output_data(array('themlist' => $theme_list));
        die;
    }

    // 获取单条主题
    public function editOp()
    {
        $theme_id = $_GET['id'];
        // 话题列表
        $where = array();
        $model = Model();
        $where['theme_id'] = $theme_id;
        if (intval($_GET['cream']) == 1) {
            $where['is_digest'] = 1;
        }
        $theme_info = $model->table('circle_theme')->where($where)->find();
        if ($theme_info['wap_imgs']) {
            $theme_info['images'] = explode(',', trim($theme_info['wap_imgs'], ','));
        }
        output_data(array("theme_list" => $theme_info));
    }

    // 删除
    public function del_themeOp()
    {
        $theme_id = $_GET['id'];
        $where['theme_id'] = $theme_id;
        $res = Model()->table('circle_theme')->where($where)->delete();
        if ($res) {
            output_data(array('status' => 1));
        } else {
            output_data(array('status' => 0));
        }
    }

    /**
     *上传多图  仅限 base64
     * @param $imgs
     * @param bool|false $dir 路径
     * @param bool|true $isdel
     * @return string
     */
    public function upImgs($imgs, $dir = false)
    {
        $dir = $dir ? $dir : date('Ymd');
        $res = '';
        foreach ($imgs as $k => $v) {
            if ( !preg_match('/image\/(.*);base64/u', $v)) {
                $res[$k] = strstr($v,'/data');
                continue;
            }
            if (file_exists($v)) {
                $res[$k] = $v;
            } else {
                $v = explode(',', $v);
                $imgpath = $dir . "/";
                preg_match('/image\/(.*);base64/u', $v[0], $imgtype);
                $imgtype = $imgtype[1] == "jpeg" ? 'jpg' : $imgtype[1];
                if (!file_exists($imgpath)) {
                    mkdir($imgpath);
                }
                list($usec, $sec) = explode(" ", microtime());
                $imgname = $sec . str_replace('0.', '_', $usec);
                $imgname = $imgname . '.' . $imgtype;
                $base64 = base64_decode(end($v));
                $save = file_put_contents($imgpath . $imgname, $base64);
                if ($save) {
                    $res[$k] = $imgpath . $imgname;
                }
            }
        }
        return $res;
    }

    /**
     * 文本过滤
     * @param $param string $subject
     * @return string
     */
    function circleCenterCensor($subject)
    {
        $replacement = '***';
        if (C('circle_wordfilter') == '') return $subject;
        $find = explode(',', C('circle_wordfilter'));
        foreach ($find as $val) {
            if (preg_match('/^\/(.+?)\/$/', $val, $a)) {
                $subject = preg_replace($val, $replacement, $subject);
            } else {
                $val = preg_replace("/\\\{(\d+)\\\}/", ".{0,\\1}", preg_quote($val, '/'));
                $subject = preg_replace("/" . $val . "/", $replacement, $subject);
            }
        }
        return $subject;
    }

    /**
     * *
     *等比缩放
     * @param unknown_type $srcImage 源图片路径
     * @param unknown_type $toFile 目标图片路径
     * @param unknown_type $maxWidth 最大宽
     * @param unknown_type $maxHeight 最大高
     * @param unknown_type $imgQuality 图片质量
     * @return unknown
     */
    function resize($srcImage, $toFile, $maxWidth = 10, $maxHeight = 10, $imgQuality = 100)
    {
        list($width, $height, $type, $attr) = getimagesize($srcImage);
//        if ($width < $maxWidth || $height < $maxHeight) return;
        switch ($type) {
            case 1:
                $img = imagecreatefromgif($srcImage);
                break;
            case 2:
                $img = imagecreatefromjpeg($srcImage);
                break;
            case 3:
                $img = imagecreatefrompng($srcImage);
                break;
        }
        $scale = min($maxWidth / $width, $maxHeight / $height); //求出绽放比例
//        if ($scale <= 1) {
            $newWidth = floor($scale * $width);
            $newHeight = floor($scale * $height);
            $newImg = imagecreatetruecolor($newWidth, $newHeight);
            imagecopyresampled($newImg, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
            $newName = "";
            $toFile = preg_replace("/(.gif|.jpg|.jpeg|.png)/i", "", $toFile);
            switch ($type) {
                case 1:
                    if (imagegif($newImg, "$toFile$newName.gif"))
                        return "$newName.gif";
                    break;
                case 2:
                    if (imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality))
                        return "$newName.jpg";
                    break;
                case 3:
                    if (imagepng($newImg, "$toFile$newName.png"))
                        return "$newName.png";
                    break;
                default:
                    if (imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality))
                        return "$newName.jpg";
                    break;
            }
            imagedestroy($newImg);
//        }
        imagedestroy($img);
        return false;
    }




}